<template>
  <div class="card">
    <el-form label-width="auto" label-position="top">
      <el-form-item label="权限名">
        <el-input v-model="code" :disabled="!!id" placeholder="请输入权限名" />
      </el-form-item>
      <el-form-item label="描述">
        <el-input v-model="desc" type="textarea" placeholder="请输入描述" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit">保存</el-button>
        <el-button @click="onCancel">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
import { getPermission, updPermission, addPermission } from '@/http'
import { useTabStore } from '@/stores'
import { useRoute } from 'vue-router'

const route = useRoute()
const tabStore = useTabStore()
const code = ref('')
const desc = ref('')

const { id } = route.params

onMounted(async () => {
  if (id) {
    const result = await getPermission(id)
    code.value = result.code
    desc.value = result.description
  }
})

const onSubmit = async () => {
  let result

  const data = {
    description: desc.value
  }

  if (id) {
    result = await updPermission(id, data)
  } else {
    result = await addPermission({
      code: code.value,
      ...data
    })
  }

  if (result) {
    tabStore.removeTab(id ? 'permission-save' : 'permission-add')
  }
}

const onCancel = () => {
  tabStore.removeTab(id ? 'permission-save' : 'permission-add')
}
</script>

<style lang="scss" scoped>
.el-form {
  max-width: 600px;
}
</style>
